package com.campus.client.net;


import com.campus.client.view.StudentRegisterFrame;
import com.campus.common.message.*;
import com.campus.common.message.*;
import com.campus.common.net.NetworkUtil;
import com.campus.common.vo.Teacher;
import com.campus.common.vo.Student;
import com.campus.common.vo.Admin;
import com.campus.common.net.NetworkUtil;
import com.campus.common.vo.Product;


import java.io.*;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.file.Files;
import java.util.List;
import java.io.IOException;

import com.campus.common.vo.Book;
/**
 * ClientConnector: 客户端连接服务器并发送请求
 */

public class ClientConnector {
    private NetworkUtil net;
    private Socket s;

    public ClientConnector(String host, int port) throws IOException {
        s = new Socket(host,port);
        net = new NetworkUtil(s);
    }
    // ========== 学生课程功能 ==========
    public StudentCourseResponse sendStudentCourseRequest(StudentCourseRequest req)
            throws IOException, ClassNotFoundException {
        net.send(req);
        Object resp = net.receive();
        if (resp instanceof StudentCourseResponse) {
            return (StudentCourseResponse) resp;
        }
        throw new IOException("Unexpected response type: " + (resp != null ? resp.getClass() : "null"));
    }

    // ========== 教师课程功能 ==========
    public TeacherCourseResponse sendTeacherCourseRequest(TeacherCourseRequest req)
            throws IOException, ClassNotFoundException {
        net.send(req);
        Object resp = net.receive();
        if (resp instanceof TeacherCourseResponse) {
            return (TeacherCourseResponse) resp;
        }
        throw new IOException("Unexpected response type: " + (resp != null ? resp.getClass() : "null"));
    }

    // ========== 管理员课程功能 ==========
    public AdminCourseResponse sendAdminCourseRequest(AdminCourseRequest req)
            throws IOException, ClassNotFoundException {
        net.send(req);
        Object resp = net.receive();
        if (resp instanceof AdminCourseResponse) {
            return (AdminCourseResponse) resp;
        }
        throw new IOException("Unexpected response type: " + (resp != null ? resp.getClass() : "null"));
    }



    // ========== 商店功能 ==========
    public ShopResponse listProducts() throws IOException, ClassNotFoundException {
        net.send(new ShopRequest("list", 0, 0, null));
        return (ShopResponse) net.receive();
    }

    public ShopResponse buyProduct(int id, int quantity, String userId) throws IOException, ClassNotFoundException {
        net.send(new ShopRequest("buy", id, quantity, userId));
        return (ShopResponse) net.receive();
    }
    
    public ShopResponse buyProducts(List<Integer> productIds, List<Integer> quantities, String userId, String password) throws IOException, ClassNotFoundException {
        net.send(new ShopRequest("buy", productIds, quantities, userId, password));
        return (ShopResponse) net.receive();
    }

    public ShopResponse addProduct(Product p) throws IOException, ClassNotFoundException {
        net.send(new ShopRequest("add", p));
        return (ShopResponse) net.receive();
    }

    public ShopResponse deleteProduct(int id) throws IOException, ClassNotFoundException {
        net.send(new ShopRequest("delete", id, 0, null));
        return (ShopResponse) net.receive();
    }

    public ShopResponse updateProduct(Product p) throws IOException, ClassNotFoundException {
        net.send(new ShopRequest("update", p));
        return (ShopResponse) net.receive();
    }

    public ShopResponse updateProductStatus(int id, int status) throws IOException, ClassNotFoundException {
        net.send(new ShopRequest("status", id, status, null));
        return (ShopResponse) net.receive();
    }

    public ShopResponse updateProductHot(int id, int hot) throws IOException, ClassNotFoundException {
        net.send(new ShopRequest("hot", id, hot, null));
        return (ShopResponse) net.receive();
    }

    public ShopResponse updateProductNew(int id, int newP) throws IOException, ClassNotFoundException {
        net.send(new ShopRequest("new", id, newP, null));
        return (ShopResponse) net.receive();
    }

    public ShopResponse updateProductExpire(int id, int expire) throws IOException, ClassNotFoundException {
        net.send(new ShopRequest("expire", id, expire, null));
        return (ShopResponse) net.receive();
    }
    
    // ========== 图片加载功能 ==========
    public UploadImageResponse uploadImage(String fileName, byte[] data) 
            throws IOException, ClassNotFoundException {
        net.send(new UploadImageRequest(fileName, data));
        return (UploadImageResponse) net.receive();
    }
    
    public String uploadImage(File file) {
        try {
            byte[] data = Files.readAllBytes(file.toPath());
            String fileName = file.getName();
            UploadImageResponse resp = uploadImage(fileName, data); // 调用原方法
            if (resp.isSuccess()) {
                return fileName; // 返回服务器保存的文件名
            } else {
                System.out.println("上传失败: " + resp.getMessage());
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public GetImageResponse getImage(String fileName) 
            throws IOException, ClassNotFoundException {
        net.send(new GetImageRequest(fileName));
        return (GetImageResponse) net.receive();
    }

    // ========== 银行功能 ==========
    public BankResponse queryBalance(String userId) throws IOException, ClassNotFoundException {
        net.send(new BankRequest("query", userId, 0));
        return (BankResponse) net.receive();
    }

    public BankResponse pay(String userId, double amount) throws IOException, ClassNotFoundException {
        net.send(new BankRequest("pay", userId, amount));
        return (BankResponse) net.receive();
    }

    public BankResponse recharge(String userId, double amount, String password) throws IOException, ClassNotFoundException {
        net.send(new BankRequest("recharge", userId, amount, password));
        return (BankResponse) net.receive();
    }

    public BankResponse openAccount(String userId, double initBalance, String password) throws IOException, ClassNotFoundException {
        net.send(new BankRequest("open", userId, initBalance, password));
        return (BankResponse) net.receive();
    }
    
    public BankResponse deleteAccount(String userId, String password) throws IOException, ClassNotFoundException {
        net.send(new BankRequest("delete", userId, 0, password));
        return (BankResponse) net.receive();
    }
    
    public BankResponse queryTransactions(String userId) throws IOException, ClassNotFoundException {
        net.send(new BankRequest("transactions", userId, 0));
        return (BankResponse) net.receive();
    }



    // ========== 管理员管理功能 ==========
    public AdminAccountManagementResponse listAdmins() throws IOException, ClassNotFoundException {
        net.send(new AdminAccountManagementRequest("list", ""));
        return (AdminAccountManagementResponse) net.receive();
    }

    public AdminAccountManagementResponse addAdmin(Admin admin) throws IOException, ClassNotFoundException {
        net.send(new AdminAccountManagementRequest("add", admin));
        return (AdminAccountManagementResponse) net.receive();
    }
    public AdminAccountManagementResponse deleteAdmin(String id) throws IOException, ClassNotFoundException {
        net.send(new AdminAccountManagementRequest("delete", id));
        return (AdminAccountManagementResponse) net.receive();
    }

    public AdminAccountManagementResponse searchAdmins(String adminId) throws IOException, ClassNotFoundException {
        net.send(new AdminAccountManagementRequest("search", adminId));
        return (AdminAccountManagementResponse) net.receive();
    }

    // ========== 教师管理功能 ==========
    public TeacherAccountManagementResponse listTeachers() throws IOException, ClassNotFoundException {
        net.send(new TeacherAccountManagementRequest("list", ""));
        return (TeacherAccountManagementResponse) net.receive();
    }

    public TeacherAccountManagementResponse addTeacher(Teacher teacher) throws IOException, ClassNotFoundException {
        net.send(new TeacherAccountManagementRequest("add", teacher));
        return (TeacherAccountManagementResponse) net.receive();
    }
    public TeacherAccountManagementResponse deleteTeacher(String id) throws IOException, ClassNotFoundException {
        net.send(new TeacherAccountManagementRequest("delete", id));
        return (TeacherAccountManagementResponse) net.receive();
    }
    public TeacherAccountManagementResponse searchTeachersById(String title) throws IOException, ClassNotFoundException {
        net.send(new TeacherAccountManagementRequest("searchByTitle", title, null));
        return (TeacherAccountManagementResponse) net.receive();
    }

    public TeacherAccountManagementResponse searchTeachersByName(String author) throws IOException, ClassNotFoundException {
        net.send(new TeacherAccountManagementRequest("searchByAuthor", null, author));
        return (TeacherAccountManagementResponse) net.receive();
    }

    public TeacherAccountManagementResponse getTeacherById(String Id) throws IOException, ClassNotFoundException {
        net.send(new TeacherAccountManagementRequest("getTeacherById", null, Id));
        System.out.print(Id);
        return (TeacherAccountManagementResponse) net.receive();
    }

    public TeacherAccountManagementResponse searchTeachers(String Id, String name) throws IOException, ClassNotFoundException {
        net.send(new TeacherAccountManagementRequest("search", Id, name));
        return (TeacherAccountManagementResponse) net.receive();
    }
    public TeacherAccountManagementResponse updateTeachers(Teacher teacher) throws IOException, ClassNotFoundException {
        net.send(new TeacherAccountManagementRequest("update", teacher));
        return (TeacherAccountManagementResponse) net.receive();
    }

    // ========== 学生管理功能 ==========
    public StudentAccountManagementResponse listStudents() throws IOException, ClassNotFoundException {
        net.send(new StudentAccountManagementRequest("list", ""));
        return (StudentAccountManagementResponse) net.receive();
    }

    public StudentAccountManagementResponse addStudent(Student student) throws IOException, ClassNotFoundException {
        net.send(new StudentAccountManagementRequest("add", student));
        return (StudentAccountManagementResponse) net.receive();
    }
    public StudentAccountManagementResponse deleteStudent(String id) throws IOException, ClassNotFoundException {
        net.send(new StudentAccountManagementRequest("delete", id));
        return (StudentAccountManagementResponse) net.receive();
    }
    public StudentAccountManagementResponse searchStudentsById(String title) throws IOException, ClassNotFoundException {
        net.send(new StudentAccountManagementRequest("searchByTitle", title, null));
        return (StudentAccountManagementResponse) net.receive();
    }

    public StudentAccountManagementResponse searchStudentsByName(String author) throws IOException, ClassNotFoundException {
        net.send(new StudentAccountManagementRequest("searchByAuthor", null, author));
        return (StudentAccountManagementResponse) net.receive();
    }

    public StudentAccountManagementResponse getStudentById(String Id) throws IOException, ClassNotFoundException {
        net.send(new StudentAccountManagementRequest("getStudentById", null, Id));
        System.out.print(Id);
        return (StudentAccountManagementResponse) net.receive();
    }

    public StudentAccountManagementResponse searchStudents(String Id, String name) throws IOException, ClassNotFoundException {
        net.send(new StudentAccountManagementRequest("search", Id, name));
        return (StudentAccountManagementResponse) net.receive();
    }
    public StudentAccountManagementResponse updateStudents(Student student) throws IOException, ClassNotFoundException {
        net.send(new StudentAccountManagementRequest("update", student));
        return (StudentAccountManagementResponse) net.receive();
    }

    public LoginResponse login(String username, String password, String role) throws IOException, ClassNotFoundException {
        net.send(new LoginRequest("login",username, password, role));
        return (LoginResponse) net.receive();
    }

    public StudentRegisterResponse register(String username,String password,Student student) throws IOException, ClassNotFoundException {
        net.send(new StudentRegisterRequest(username,password,student));
        return (StudentRegisterResponse) net.receive();
    }

    public TeacherRegisterResponse register(String username, String password, Teacher teacher) throws IOException, ClassNotFoundException {
        net.send(new TeacherRegisterRequest(username,password,teacher));
        return (TeacherRegisterResponse) net.receive();
    }

    public PasswordChangeResponse changePassword(String username, String newPassword) throws IOException, ClassNotFoundException {
        net.send(new PasswordChangeRequest(username,newPassword));
        return (PasswordChangeResponse) net.receive();
    }

    // ========== 图书馆功能 ==========
    public LibraryResponse listBooks() throws IOException, ClassNotFoundException {
        net.send(new LibraryRequest("list", 0));
        return (LibraryResponse) net.receive();
    }
    public LibraryResponse getUserBorrowedBooks(String username) throws IOException, ClassNotFoundException {
        net.send(new LibraryRequest("getBorrowList", username));
        return (LibraryResponse) net.receive();
    }
    public LibraryResponse getBookBorrowers(int bookId) throws IOException, ClassNotFoundException {
        net.send(new LibraryRequest("getBorrowersById", bookId, true));
        return (LibraryResponse) net.receive();
    }
    public LibraryResponse getUserBorrowRecords(String username) throws IOException, ClassNotFoundException {
        net.send(new LibraryRequest("getBorrowRecords", username));
        return (LibraryResponse) net.receive();
    }
    public LibraryResponse borrowBook(int id, String username) throws IOException, ClassNotFoundException {
        net.send(new LibraryRequest("borrow", id, username));
        return (LibraryResponse) net.receive();
    }

    public LibraryResponse returnBook(int id, String username) throws IOException, ClassNotFoundException {
        net.send(new LibraryRequest("return", id, username));
        return (LibraryResponse) net.receive();
    }
    public LibraryResponse addBook(Book book) throws IOException, ClassNotFoundException {
        net.send(new LibraryRequest("add", book));
        return (LibraryResponse) net.receive();
    }
    public LibraryResponse deleteBook(int id) throws IOException, ClassNotFoundException {
        net.send(new LibraryRequest("delete", id));
        return (LibraryResponse) net.receive();
    }
    public LibraryResponse searchBooksByTitle(String title) throws IOException, ClassNotFoundException {
        net.send(new LibraryRequest("searchByTitle", title, null));
        return (LibraryResponse) net.receive();
    }

    public LibraryResponse searchBooksByAuthor(String author) throws IOException, ClassNotFoundException {
        net.send(new LibraryRequest("searchByAuthor", null, author));
        return (LibraryResponse) net.receive();
    }

    public LibraryResponse searchBooks(String title, String author) throws IOException, ClassNotFoundException {
        net.send(new LibraryRequest("search", title, author));
        return (LibraryResponse) net.receive();
    }
    public LibraryResponse updateBook(Book book) throws IOException, ClassNotFoundException {
        net.send(new LibraryRequest("update", book));
        return (LibraryResponse) net.receive();
    }
    public LibraryResponse searchBooksByCategory(String category) throws IOException, ClassNotFoundException {
        net.send(new LibraryRequest("searchByCategory", category, true));
        return (LibraryResponse) net.receive();
    }

    // 新增获取所有类别方法
    public LibraryResponse getAllCategories() throws IOException, ClassNotFoundException {
        net.send(new LibraryRequest("getAllCategories", (Book) null));
        return (LibraryResponse) net.receive();
    }

    public StudentChangeInfoResponse addRequest(String studentId,String cotnactInfo,String oldContactInfo) throws IOException, ClassNotFoundException {
        net.send(new StudentChangeInfoRequest("add", studentId, cotnactInfo, oldContactInfo));
        return (StudentChangeInfoResponse) net.receive();
    }

    public StudentChangeInfoResponse deleteRequest(String studentId,String cotnactInfo) throws IOException, ClassNotFoundException {
        net.send(new StudentChangeInfoRequest("delete", studentId, cotnactInfo, null));
        return (StudentChangeInfoResponse) net.receive();
    }

    public StudentChangeInfoResponse listRequests() throws IOException, ClassNotFoundException {
        net.send(new StudentChangeInfoRequest("list","","",""));
        return (StudentChangeInfoResponse) net.receive();
    }

    public StudentChangeInfoResponse updateStudentInfo(String id,String contactInfo) throws IOException, ClassNotFoundException {
        net.send(new StudentChangeInfoRequest("update", id, contactInfo,""));
        return (StudentChangeInfoResponse) net.receive();
    }

    public TeacherChangeInfoResponse addTeacherRequest(String teacherId,String cotnactInfo,String oldContactInfo) throws IOException, ClassNotFoundException {
        net.send(new TeacherChangeInfoRequest("add", teacherId, cotnactInfo, oldContactInfo));
        return (TeacherChangeInfoResponse) net.receive();
    }

    public TeacherChangeInfoResponse deleteTeacherRequest(String teacherId,String cotnactInfo) throws IOException, ClassNotFoundException {
        net.send(new TeacherChangeInfoRequest("delete", teacherId, cotnactInfo, null));
        return (TeacherChangeInfoResponse) net.receive();
    }

    public TeacherChangeInfoResponse listTeacherRequests() throws IOException, ClassNotFoundException {
        net.send(new TeacherChangeInfoRequest("list","","",""));
        return (TeacherChangeInfoResponse) net.receive();
    }

    public TeacherChangeInfoResponse updateTeacherInfo(String id,String contactInfo) throws IOException, ClassNotFoundException {
        net.send(new TeacherChangeInfoRequest("update", id, contactInfo,""));
        return (TeacherChangeInfoResponse) net.receive();
    }



    public void close() throws IOException {
        net.close();
    }

}

